﻿#region Using Statements
using GameBase.Graphics;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
#endregion

namespace StarFox.Graphics
{
    /// <summary>
    /// Performs motion blur post-processing.
    /// </summary>
    internal class MotionBlurProcessor
    {
        #region Fields

        Effect effect;
        EffectParameter blurFactor;
        
        GraphicsDevice GraphicsDevice;
        QuadRenderer quad;
        
        #endregion

        #region Properties

        /// <summary>
        /// Sets the motion blur factor.
        /// </summary>
        public float BlurFactor { set { blurFactor.SetValue(value); } }

        #endregion

        #region Constructor

        /// <summary>
        /// Initializes a new instance of this class.
        /// </summary>
        /// <param name="effect">The motion blur post-processing effect.</param>
        public MotionBlurProcessor(Effect effect)
        {
            this.effect = effect;
            GraphicsDevice = effect.GraphicsDevice;
            quad = new QuadRenderer(GraphicsDevice);

            blurFactor = effect.Parameters["BlurFactor"];

            Vector2 pixelSize = new Vector2(1.0f / (float)GraphicsDevice.PresentationParameters.BackBufferWidth,
                                            1.0f / (float)GraphicsDevice.PresentationParameters.BackBufferHeight);

            effect.Parameters["HalfPixelOffset"].SetValue(pixelSize * 0.5f);
        }

        #endregion

        #region Apply

        /// <summary>
        /// Applies the motion blur post-processing effect.
        /// </summary>
        /// <param name="inTexture">Texture2D used as processing input.</param>
        /// <param name="outRenderTarget">RenderTarget2D used as processing output.</param>
        public void Apply(Texture2D inTexture, RenderTarget2D outRenderTarget)
        {
            GraphicsDevice.SetRenderTarget(outRenderTarget);
            GraphicsDevice.BlendState = BlendState.Opaque;
            GraphicsDevice.DepthStencilState = DepthStencilState.None;
            GraphicsDevice.RasterizerState = RasterizerState.CullCounterClockwise;
            GraphicsDevice.Clear(Color.Transparent);

            effect.Parameters["SceneMap"].SetValue(inTexture);
            effect.CurrentTechnique.Passes[0].Apply();
            quad.Draw();
        }

        #endregion
    }
}
